import React, { useState, useRef } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import { styled } from '@mui/material/styles';
import DownloadIcon from '@mui/icons-material/Download';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';

// 定义图片状态接口
interface ImageState {
  original: string | null;
  processed: string | null;
  isProcessing: boolean;
  fileName: string | null;
}

// 定义背景类别接口
interface BackgroundCategory {
  id: string;
  title: string;
  description: string;
  colors: string[];
}

// 样式组件
const AppContainer = styled('div')({
  display: 'flex',
  flexDirection: 'column',
  minHeight: '100vh',
  backgroundColor: '#f8f9fa',
});

const Header = styled('header')(({ theme }) => ({
  position: 'sticky',
  top: 0,
  zIndex: 1000,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
  padding: theme.spacing(2, 3),
  backgroundColor: '#ffffff',
  boxShadow: '0 2px 10px rgba(0,0,0,0.1)',
}));

const Content = styled('div')(({ theme }) => ({
  display: 'flex',
  flex: 1,
  padding: theme.spacing(3),
  gap: theme.spacing(3),
  maxWidth: 1400,
  margin: '0 auto',
  width: '100%',
  flexWrap: 'wrap',
}));

const LeftPanel = styled('div')({
  flex: 3,
  display: 'flex',
  flexDirection: 'column',
  gap: '16px',
  minWidth: 300,
});

const RightPanel = styled('div')({
  flex: 2,
  display: 'flex',
  flexDirection: 'column',
  gap: '16px',
  minWidth: 250,
});

const Footer = styled('footer')(({ theme }) => ({
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  padding: theme.spacing(2, 3),
  backgroundColor: '#ffffff',
  borderTop: '1px solid #eaeaea',
}));

const SectionCard = styled(Box)({
  background: '#ffffff',
  borderRadius: 8,
  boxShadow: '0 2px 10px rgba(0,0,0,0.08)',
  overflow: 'hidden',
});

const SectionHeader = styled(Box)({
  padding: '16px 20px',
  borderBottom: '1px solid #f0f0f0',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
});

const UploadPrompt = styled(Box)({
  border: '2px dashed #e0e0e0',
  borderRadius: 8,
  padding: '40px 20px',
  textAlign: 'center',
  cursor: 'pointer',
  transition: 'all 0.3s',
  backgroundColor: '#fafafa',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  
  '&:hover': {
    borderColor: '#1976d2',
    backgroundColor: '#f0f7ff',
  },
  
  '& .icon': {
    fontSize: 48,
    color: '#1976d2',
    marginBottom: 16,
  },
});

const ImagePreview = styled(Box)({
  border: '1px solid #e0e0e0',
  borderRadius: 4,
  height: 300,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  overflow: 'hidden',
  position: 'relative',
  backgroundColor: '#f8f8f8',
  
  '& .bg-pattern': {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundImage: 
      'linear-gradient(45deg, #f5f5f5 25%, transparent 25%, transparent 75%, #f5f5f5 75%), ' +
      'linear-gradient(45deg, #f5f5f5 25%, transparent 25%, transparent 75%, #f5f5f5 75%)',
    backgroundSize: '20px 20px',
    backgroundPosition: '0 0, 10px 10px',
    zIndex: 0,
  },
  
  '& img': {
    position: 'relative',
    maxWidth: '100%',
    maxHeight: '100%',
    zIndex: 1,
  },
});

const Cut = () => {
  // 初始化图片状态
  const [image, setImage] = useState<ImageState>({
    original: null,
    processed: null,
    isProcessing: false,
    fileName: null,
  });
  
  // 初始化活动类别和下载格式
  const [activeCategory, setActiveCategory] = useState('scenery');
  const [downloadFormat, setDownloadFormat] = useState('png');
  
  // 创建文件输入引用
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 背景类别配置
  const categories: BackgroundCategory[] = [
    {
      id: 'scenery',
      title: '山水风景',
      description: '山水、风景、建筑、城市、自然等美景',
      colors: ['#FF9A8B', '#FF6A88', '#FF99AC']
    },
    {
      id: 'style',
      title: '风格文字',
      description: '东欧、魔幻、学城或风情城风格',
      colors: ['#6A11CB', '#2575FC', '#3A7BD5']
    },
    {
      id: 'electronic',
      title: '电子产品',
      description: '电脑、手机、键盘、鼠标等电子产品',
      colors: ['#11998E', '#38EF7D', '#43CBFF']
    }
  ];

  // 处理图片上传
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    
    // 设置图片状态为处理中
    setImage({ 
      original: null,
      processed: null,
      isProcessing: true,
      fileName: file.name,
    });

    // 读取文件内容
    const reader = new FileReader();
    reader.onload = async (e) => {
      const imageData = e.target?.result as string;
      // 设置图片状态为原始图片
      setImage(prev => ({
        ...prev,
        original: imageData,
      }));
      
      // 开始抠图处理
      try {
        // 模拟抠图处理过程
        const processedImage = await simulateRemBg(imageData);
        // 设置图片状态为处理后的图片
        setImage(prev => ({
          ...prev,
          processed: processedImage,
          isProcessing: false,
        }));
      } catch (error) {
        console.error('Background removal failed:', error);
        // 设置图片状态为处理失败
        setImage(prev => ({
          ...prev,
          isProcessing: false,
        }));
      }
    };
    reader.readAsDataURL(file);
  };

  // 模拟 rembg API 的函数
  const simulateRemBg = (imageData: string): Promise<string> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const img = new Image();
        img.src = imageData;
        
        img.onload = () => {
          const canvas = document.createElement('canvas');
          canvas.width = img.width;
          canvas.height = img.height;
          
          const ctx = canvas.getContext('2d');
          if (ctx) {
            ctx.drawImage(img, 0, 0);
            
            // 使用更高级的抠图算法
            const processed = advancedBackgroundRemoval(ctx, img.width, img.height);
            resolve(processed);
          } else {
            resolve(imageData);
          }
        };
      }, 1500);
    });
  };

  // 高级抠图算法实现
  const advancedBackgroundRemoval = (ctx: CanvasRenderingContext2D, width: number, height: number): string => {
    const imageData = ctx.getImageData(0, 0, width, height);
    const data = imageData.data;
    
    // 获取四角颜色作为背景参考
    const corners = [
      {x: 0, y: 0},                   // 左上角
      {x: width - 1, y: 0},           // 右上角
      {x: 0, y: height - 1},          // 左下角
      {x: width - 1, y: height - 1}   // 右下角
    ];
    
    let rTotal = 0, gTotal = 0, bTotal = 0;
    
    for (const {x, y} of corners) {
      const idx = (y * width + x) * 4;
      rTotal += data[idx];
      gTotal += data[idx + 1];
      bTotal += data[idx + 2];
    }
    
    const bgR = Math.floor(rTotal / corners.length);
    const bgG = Math.floor(gTotal / corners.length);
    const bgB = Math.floor(bTotal / corners.length);
    
    // 去除背景
    const threshold = 50;
    const edgeRadius = 3;
    
    for (let i = 0; i < data.length; i += 4) {
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      
      // 计算与背景颜色的差距
      const diff = Math.abs(r - bgR) + Math.abs(g - bgG) + Math.abs(b - bgB);
      
      if (diff < threshold) {
        // 标记为背景
        data[i + 3] = 0;
      } else {
        // 处理边缘
        const x = (i / 4) % width;
        const y = Math.floor((i / 4) / width);
        
        let bgNeighbors = 0;
        
        // 检查周围像素
        for (let dy = -edgeRadius; dy <= edgeRadius; dy++) {
          for (let dx = -edgeRadius; dx <= edgeRadius; dx++) {
            if (dx === 0 && dy === 0) continue;
            
            const nx = x + dx;
            const ny = y + dy;
            
            if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
              const nIdx = (ny * width + nx) * 4;
              
              // 计算邻居颜色与背景的差距
              const nDiff = Math.abs(data[nIdx] - bgR) + 
                           Math.abs(data[nIdx + 1] - bgG) + 
                           Math.abs(data[nIdx + 2] - bgB);
              
              if (nDiff < threshold) {
                bgNeighbors++;
              }
            }
          }
        }
        
        // 如果周围有很多背景像素，设为半透明
        if (bgNeighbors > 0) {
          data[i + 3] = 255 - (bgNeighbors * 20);
        }
      }
    }
    
    ctx.putImageData(imageData, 0, 0);
    return ctx.canvas.toDataURL('image/png');
  };

  // 触发文件选择
  const triggerFileSelect = () => {
    fileInputRef.current?.click();
  };

  // 下载图片
  const downloadImage = () => {
    if (!image.processed) return;
    
    // 设置下载格式
    const extension = downloadFormat === 'png' ? 'png' : 'jpg';
    const fileName = image.fileName 
      ? `cutout-${image.fileName.replace(/\.[^/.]+$/, '')}.${extension}`
      : `cutout.${extension}`;
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = image.processed;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <AppContainer>
      <Header>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <Box sx={{ 
            fontSize: { xs: '1.2rem', sm: '1.6rem' }, 
            fontWeight: 'bold', 
            color: '#1976d2' 
          }}>
            包图网
          </Box>
          <Box sx={{ 
            fontSize: { xs: '0.7rem', sm: '0.9rem' }, 
            ml: 1, 
            color: '#666' 
          }}>
            旗舰版
          </Box>
        </Box>
        <Box sx={{ 
          fontSize: { xs: '0.9rem', sm: '1.1rem' }, 
          fontWeight: 500,
          display: { xs: 'none', sm: 'block' }
        }}>
          一键智能搜图 / AI精准内容识别 / 极速下载
        </Box>
        <Button
          variant="contained"
          color="primary"
          startIcon={<CloudUploadIcon />}
          onClick={triggerFileSelect}
          sx={{ 
            fontWeight: 'bold',
            textTransform: 'none',
            fontSize: { xs: '0.8rem', sm: '1rem' }
          }}
        >
          上传图片
        </Button>
      </Header>
      
      <Content>
        <LeftPanel>
          <SectionCard>
            <SectionHeader>
              <Box sx={{ fontWeight: 'bold', fontSize: '1.2rem' }}>图片抠图</Box>
            </SectionHeader>
            
            <Box sx={{ p: 2 }}>
              <input 
                type="file"
                ref={fileInputRef}
                onChange={handleImageUpload}
                style={{ display: 'none' }}
                accept="image/*"
              />
              
              {image.original ? (
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                  <Box sx={{ 
                    display: 'flex', 
                    flexWrap: 'wrap', 
                    gap: 3,
                    justifyContent: 'center'
                  }}>
                    <Box sx={{ flex: '1 1 300px' }}>
                      <Box sx={{ fontWeight: 500, mb: 1, color: '#555' }}>原始图片</Box>
                      <ImagePreview>
                        <div className="bg-pattern"></div>
                        <img 
                          src={image.original} 
                          alt="Original" 
                          style={{ maxHeight: 300 }}
                        />
                      </ImagePreview>
                      {image.fileName && (
                        <Box sx={{ 
                          mt: 1, 
                          fontSize: 14, 
                          color: '#666', 
                          textAlign: 'center'
                        }}>
                          {image.fileName}
                        </Box>
                      )}
                    </Box>
                    
                    <Box sx={{ flex: '1 1 300px' }}>
                      <Box sx={{ fontWeight: 500, mb: 1, color: '#555' }}>抠图结果</Box>
                      <ImagePreview>
                        <div className="bg-pattern"></div>
                        {image.isProcessing ? (
                          <Box sx={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center',
                            backgroundColor: 'rgba(255,255,255,0.8)',
                            zIndex: 10
                          }}>
                            <CircularProgress color="primary" size={40} />
                            <Box sx={{ mt: 2, fontWeight: 500 }}>AI抠图处理中...</Box>
                          </Box>
                        ) : null}
                        
                        {image.processed ? (
                          <img 
                            src={image.processed} 
                            alt="Processed" 
                            style={{ maxHeight: 300 }}
                          />
                        ) : (
                          <Box sx={{ 
                            display: 'flex', 
                            flexDirection: 'column', 
                            alignItems: 'center',
                            color: '#888'
                          }}>
                            <Box sx={{ 
                              width: 80, 
                              height: 80, 
                              borderRadius: '50%',
                              border: '2px dashed #ccc',
                              mb: 1
                            }}></Box>
                            <Box>等待处理结果</Box>
                          </Box>
                        )}
                      </ImagePreview>
                      
                      {image.processed && (
                        <Box sx={{ 
                          mt: 1, 
                          display: 'flex', 
                          alignItems: 'center',
                          justifyContent: 'center',
                          gap: 1
                        }}>
                          <Box sx={{ fontSize: 14 }}>下载格式:</Box>
                          <Box sx={{ 
                            display: 'flex',
                            gap: 1,
                            '& .format-option': {
                              padding: '4px 8px',
                              borderRadius: 4,
                              cursor: 'pointer',
                              transition: 'all 0.2s',
                              '&:hover': {
                                backgroundColor: '#e3f2fd'
                              },
                              '&.active': {
                                backgroundColor: '#bbdefb',
                                fontWeight: '500'
                              }
                            }
                          }}>
                            <Box 
                              className={`format-option ${downloadFormat === 'png' ? 'active' : ''}`}
                              onClick={() => setDownloadFormat('png')}
                            >
                              PNG
                            </Box>
                            <Box 
                              className={`format-option ${downloadFormat === 'jpg' ? 'active' : ''}`}
                              onClick={() => setDownloadFormat('jpg')}
                            >
                              JPG
                            </Box>
                          </Box>
                        </Box>
                      )}
                    </Box>
                  </Box>
                  
                  {image.processed && (
                    <Box sx={{ display: 'flex', justifyContent: 'center', mt: 1 }}>
                      <Button
                        variant="contained"
                        color="success"
                        startIcon={<DownloadIcon />}
                        onClick={downloadImage}
                        sx={{ 
                          padding: '8px 24px',
                          fontWeight: 'bold',
                          textTransform: 'none',
                          fontSize: '1rem'
                        }}
                      >
                        下载抠图结果
                      </Button>
                    </Box>
                  )}
                </Box>
              ) : (
                <UploadPrompt onClick={triggerFileSelect}>
                  <CloudUploadIcon className="icon" />
                  <Box sx={{ fontSize: 18, fontWeight: 500, mb: 1 }}>上传图片</Box>
                  <Box sx={{ color: '#888', fontSize: 14, mb: 2 }}>
                    支持 JPG, PNG 格式 (最大 10MB)
                  </Box>
                  <Button variant="outlined" color="primary">
                    选择文件
                  </Button>
                </UploadPrompt>
              )}
            </Box>
          </SectionCard>
          
          <SectionCard>
            <SectionHeader>
              <Box sx={{ fontWeight: 'bold', fontSize: '1.2rem' }}>智能识别背景</Box>
              <Box sx={{ fontSize: '0.8rem', color: '#666', fontStyle: 'italic' }}>
                自动推荐适合的背景类别
              </Box>
            </SectionHeader>
            
            <Box sx={{ display: 'flex', gap: 2, p: 2 }}>
              <Box sx={{ flex: 1, borderRadius: 1, overflow: 'hidden' }}>
                <Box 
                  sx={{
                    height: 180,
                    backgroundImage: `linear-gradient(135deg, ${categories.find(c => c.id === activeCategory)?.colors?.[0]} 0%, ${categories.find(c => c.id === activeCategory)?.colors?.[1]} 50%, ${categories.find(c => c.id === activeCategory)?.colors?.[2]} 100%)`,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    position: 'relative',
                    overflow: 'hidden'
                  }}
                >
                  {image.processed ? (
                    <img 
                      src={image.processed} 
                      alt="Background preview"
                      style={{ 
                        maxWidth: '80%', 
                        maxHeight: '80%',
                        boxShadow: '0 4px 20px rgba(0,0,0,0.2)',
                        borderRadius: 4
                      }}
                    />
                  ) : (
                    <Box sx={{ 
                      textAlign: 'center', 
                      color: 'rgba(255,255,255,0.7)',
                      p: 2
                    }}>
                      处理后将自动识别适合的背景类别
                    </Box>
                  )}
                </Box>
                <Box sx={{ 
                  p: 2, 
                  backgroundColor: '#f5f7fa', 
                  fontSize: '0.9rem',
                  height: 80 
                }}>
                  {categories.find(c => c.id === activeCategory)?.description}
                </Box>
              </Box>
              
              <Box sx={{ width: 160 }}>
                {categories.map(category => (
                  <Box 
                    key={category.id}
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      padding: '12px 16px',
                      cursor: 'pointer',
                      borderRadius: '4px',
                      marginBottom: '6px',
                      transition: 'all 0.2s',
                      backgroundColor: activeCategory === category.id ? '#e3f2fd' : 'transparent',
                      fontWeight: activeCategory === category.id ? 500 : 400,
                      '&:hover': {
                        backgroundColor: '#e3f2fd',
                      }
                    }}
                    onClick={() => setActiveCategory(category.id)}
                  >
                    <Box sx={{
                      width: 16,
                      height: 16,
                      backgroundColor: category.colors[0],
                      borderRadius: '50%',
                      mr: 1
                    }} />
                    {category.title}
                  </Box>
                ))}
              </Box>
            </Box>
          </SectionCard>
        </LeftPanel>
        
        <RightPanel>
          <SectionCard>
            <SectionHeader>
              <Box sx={{ fontWeight: 'bold', fontSize: '1.2rem' }}>功能区</Box>
            </SectionHeader>
            
            <Box sx={{ p: 2 }}>
              <Box sx={{ mb: 3 }}>
                <Box sx={{ fontWeight: 500, mb: 1, fontSize: '1rem' }}>背景搜索</Box>
                <Box sx={{ display: 'flex' }}>
                  <input 
                    type="text" 
                    placeholder="输入关键词搜索背景..." 
                    style={{
                      flex: 1,
                      padding: '10px 14px',
                      border: '1px solid #e0e0e0',
                      borderRight: 0,
                      borderRadius: '4px 0 0 4px',
                      fontSize: '14px',
                      outline: 'none'
                    }}
                  />
                  <button 
                    style={{
                      padding: '10px 20px',
                      background: '#1976d2',
                      color: 'white',
                      border: 'none',
                      borderRadius: '0 4px 4px 0',
                      cursor: 'pointer',
                      fontSize: '14px',
                      fontWeight: 500
                    }}
                  >
                    搜索
                  </button>
                </Box>
              </Box>
              
              <Box sx={{ mb: 3 }}>
                <Box sx={{ 
                  fontWeight: 500, 
                  mb: 1,
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span>推荐背景</span>
                  <Box sx={{ 
                    fontSize: '0.8rem', 
                    color: '#1976d2', 
                    cursor: 'pointer'
                  }}>
                    更多
                  </Box>
                </Box>
                <Box 
                  sx={{ 
                    display: 'grid', 
                    gridTemplateColumns: 'repeat(3, 1fr)',
                    gap: '10px'
                  }}
                >
                  {[1, 2, 3].map((index) => (
                    <Box 
                      key={index} 
                      sx={{ 
                        backgroundColor: '#f8f8f8',
                        borderRadius: '4px',
                        overflow: 'hidden',
                        aspectRatio: '1/1',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        cursor: 'pointer',
                        transition: 'transform 0.2s',
                        border: '1px solid #eee',
                        '&:hover': {
                          transform: 'scale(1.03)',
                          boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
                        }
                      }}
                    >
                      <Box sx={{ 
                        color: '#999',
                        fontSize: '0.7rem',
                        textAlign: 'center',
                        padding: 1
                      }}>
                        背景 {index}
                      </Box>
                    </Box>
                  ))}
                </Box>
              </Box>
              
              <Box sx={{ mb: 3 }}>
                <Box sx={{ 
                  fontWeight: 500, 
                  mb: 1,
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span>热门背景</span>
                  <Box sx={{ 
                    fontSize: '0.8rem', 
                    color: '#1976d2', 
                    cursor: 'pointer'
                  }}>
                    更多
                  </Box>
                </Box>
                <Box 
                  sx={{ 
                    display: 'grid', 
                    gridTemplateColumns: 'repeat(3, 1fr)',
                    gap: '10px'
                  }}
                >
                  {[4, 5, 6].map((index) => (
                    <Box 
                      key={index} 
                      sx={{ 
                        backgroundColor: '#f8f8f8',
                        borderRadius: '4px',
                        overflow: 'hidden',
                        aspectRatio: '1/1',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        cursor: 'pointer',
                        transition: 'transform 0.2s',
                        border: '1px solid #eee',
                        '&:hover': {
                          transform: 'scale(1.03)',
                          boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
                        }
                      }}
                    >
                      <Box sx={{ 
                        color: '#999',
                        fontSize: '0.7rem',
                        textAlign: 'center',
                        padding: 1
                      }}>
                        背景 {index}
                      </Box>
                    </Box>
                  ))}
                </Box>
              </Box>
              
              <Box>
                <Box sx={{ fontWeight: 500, mb: 1 }}>支持说明</Box>
                <Box sx={{ 
                  fontSize: '0.9rem', 
                  color: '#666',
                  padding: '12px',
                  backgroundColor: '#f5f7fa',
                  borderRadius: '4px',
                  lineHeight: 1.5
                }}>
                  <p>• 支持格式: PNG, JPG, JPEG</p>
                  <p>• 最大上传: 10MB</p>
                  <p>• 分辨率: 100px-4000px</p>
                  <p>• 处理时间: 约1-5秒</p>
                  <p>• 背景智能识别功能需先抠图处理</p>
                </Box>
              </Box>
            </Box>
          </SectionCard>
        </RightPanel>
      </Content>
      
      <Footer>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <Box sx={{ 
            fontWeight: 'bold', 
            fontSize: '1.2rem', 
            color: '#1976d2' 
          }}>
            包图网
          </Box>
          <Box sx={{ 
            fontSize: '0.9rem', 
            ml: 1, 
            color: '#666',
            display: { xs: 'none', sm: 'block' } 
          }}>
            人机界面 · 轻松浏览、查找、评论、购物
          </Box>
        </Box>
        <Box sx={{ 
          fontSize: '0.9rem', 
          color: '#666'
        }}>
          © 2023 包图抠图神器
        </Box>
      </Footer>
    </AppContainer>
  );
};

export default Cut;